#!/usr/bin/env python
"""Provides ...

funktioniert dann noch Unit-Testing

-->
Picture = "Where should the chart saved?"
FileName = {'type': "System.String", 'description': "The file you like to save.", 'validation': "IsFile"}
ImgWidth = {'type': "System.Int32", 'description': "The width of the image."}
ImgHeight = {'type': "System.Int32", 'description': "The height of the image."}
ChartType = {'type': "System.String", 'description': "The type of the chart (see Google Chart Tools)."}
-->

-->
ChartData = "Which Data should use to draw the new chart?"
-->

-->
ChartLegend = "The Headline for every given chart data."
Name = {'type': "System.String", 'description': "The data headline."}
-->
"""

from MyClever.Lib import *
import urllib

__author__ = "Mathias Mielitz"
__copyright__ = "Copyright 2011, MyCleverFriend.com"
__credits__ = ["Mathias Mielitz"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Mathias Mielitz"
__email__ = "m.mielitz@adrabbit.de"
__status__ = "Production"
__description__ = "Draws a chart by using the expected data with the Google Chart API."

class GoogleChart(MissionPlugin):
	def Work(self):
		"""All very experimental..."""
		
		self.data = {}
		self.maxInt = 0;
		self.legend = ''
		
		picturePackage = self.GetDataReader("Picture")
		while picturePackage.Read():
			# get all data
			dataPackage = self.GetDataReader("ChartData")				
			while dataPackage.Read():
				for columnOn in self.GetColumnNames(dataPackage):
					# prepare the data dictionary
					if not columnOn.Key.ToString() in self.data:
						self.data[columnOn.Key.ToString()] = ''
					# ... and save the data value
					self.data[columnOn.Key.ToString()] += dataPackage[columnOn.Key.ToString()] + ','
					
					if int(dataPackage[columnOn.Key.ToString()]) > self.maxInt:
						self.maxInt = int(dataPackage[columnOn.Key.ToString()])
			
			legendsPackage = self.GetDataReader("ChartLegend")		
			while legendsPackage.Read():
				self.legend += legendsPackage['Name'] + '|'
			
			params = urllib.urlencode({
				'cht': picturePackage["ChartType"].ToString(),
				'chs': picturePackage["ImgWidth"].ToString() + 'x' + picturePackage["ImgHeight"].ToString(),
				'chd': self.GetDataString(),
				'chds': '0,' + str(self.maxInt),
				'chdl': self.legend[:-1]
			})

			self.AddNewLoggingMessage("Picture", "draw: " + picturePackage["FileName"].ToString() + " (" + picturePackage["ImgWidth"].ToString() + "x" + picturePackage["ImgHeight"].ToString() + ")")	

			fileObj = open(picturePackage["FileName"].ToString(),"wb")
			fileObj.write(urllib.urlopen('http://chart.apis.google.com/chart?', params).read())
			fileObj.close()
		
	def GetDataString(self):
		result = 't:'
		for columnOn in self.data:
			result += self.data[columnOn][:-1] + '|'
		return result[:-1]